package com.jiangfeixiang.springbootblog.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: 姜飞祥
 * @Description: 登录校验Aop
 * @Date: Create in 2019/1/26/0026 10:50
 * @param: $params$
 * @return: $returns$
 */
@Aspect
@Component
public class UserLoginAop {

    @Before("execution(* com.jiangfeixiang.springbootblog.controller.admin.*.*(..))")
    public String loginCheck(){

        //获取session对象，判断用户是否已经登录
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user !=null){
            System.out.println("user不为空"+user);
            return "redirect:/admin/index";
        }
        //如果session中没有User对象，则跳转到登录页面
        return "redirect:/admin/";
    }
}
